/*
 * MyClient.java
 *
 * Created on 23. leden 2007, 15:18
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package cz.results.perzist.db4ocs;

//import com.db4o.Db4o;
//import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.cs.client.Db4oClient;
import java.io.IOException;
import java.util.Iterator;
// import java.io.IOException;

public class DbClientDb4oCS {
    private static final String HOST = "localhost";
    private static final int PORT = 4488;
    private static final String USER = "test";
    private static final String PASWD = "test";
    
    private static Db4oClient dbClient = null;
    
    public static Db4oClient dbGetClient() throws IOException {
        if (dbClient == null) {
            dbClient = new Db4oClient(HOST,PORT);
            dbClient.connect();
            dbClient.login(USER,PASWD);
        }
        return dbClient;
    }
    
    public static void dbCloseClient() {
        if (dbClient != null) {
            dbClient.close();
            dbClient = null;
        }
    }
    
    public static void dbWrite(Object ob) throws IOException {
        dbGetClient().set(ob);
        dbGetClient().commit();
    }
    
    public static ObjectSet dbRead(Object ob) throws IOException {
        return dbGetClient().get(ob);
    }
    
    public static void dbDelete(Object ob) throws IOException {
        dbGetClient().delete(ob);
        dbGetClient().commit();
    }
    
    
    public static void dbZap(Object ob) throws IOException {
        ObjectSet os = dbRead(ob);
        for (Iterator i = os.iterator(); i.hasNext();) {
            dbDelete(i.next());
        }
    }
    
    public static void dbZapFile() throws IOException {
        dbZap(new Object());
    }
    
    public static int dbRecCount(Object ob) throws IOException {
        ObjectSet os = dbRead(ob);
        return os.size();
    }
    
}



